<template>
  <div class="login">
    <!--页头 -->
    <!-- <Header></Header> --> 
    <!-- 根据单点登录页面重新布局 -->
    <div class="loginBox">
      <img src="~@/assets/logo/denglu.png" alt="">
      <span>地震灾害风险防治产品信息服务</span>
    </div>
    <!-- 表单 -->
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">
        <span>用户登录</span>
        <router-link class="go-register" to="/register">
          <el-icon>
            <CaretRight />
          </el-icon>立即注册
        </router-link>
      </h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号">
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码"
          @keyup.enter="handleLogin">
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaOnOff">
        <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%"
          @keyup.enter="handleLogin">
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>
      <el-form-item class="password-set">
        <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
        <router-link class="forgot-password" to="/forgotPassword">忘记密码？</router-link>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button :loading="loading" size="large" type="primary" style="width:100%;" @click.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/ '">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!-- 页脚 -->
    <Footer></Footer>
  </div>
</template>

<script setup>
// 引入页头组件
import Header from "@/components/Header/LoginHeader";
// 引入底部组件
import Footer from "@/components/Footer";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
// 用户状态
import useUserStore from '@/store/modules/user';
// 引入接口
import { getCodeImg } from "@/api/login";
import { onMounted } from "vue";

// 当前实例
const { proxy } = getCurrentInstance();
// 用户状态
const userStore = useUserStore()
// 全局路由
const router = useRouter();
// 当前路由
const route = useRoute();

// 登录表单
const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: ""
});
// 表单验证规则
const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

// 加载动画
const loading = ref(false);
// 验证码路径
const codeUrl = ref("");
// 验证码开关
const captchaOnOff = ref(false);
// 注册开关
const register = ref(false);
// 重定向
const redirect = ref(undefined);

// 登录操作
function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在cookie中设置记住用户明和名命
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        // 判断是否有toUrl用作跳转
        if (route.query?.toUrl) {
          location.href = route.query.toUrl;
        } else {
          router.push({ path: redirect.value || "/" });
          
        }
      }).catch((err) => {
        proxy.$modal.msgError(err||'登录失败！');
        loading.value = false;
        // 重新获取验证码
        if (captchaOnOff.value) {
          getCode();
        }
      });
    }
  });
}
// 获取验证码
function getCode() {
  getCodeImg().then(res => {
    captchaOnOff.value = res.captchaOnOff === undefined ? true : res.captchaOnOff;
    if (captchaOnOff.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}
// 获取Cookie
function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

// 挂载
onMounted(() => {
  if (captchaOnOff.value) {
    // 获取验证码
    getCode();
  }
  // 获取Cookie
  getCookie();
})
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  // background-image: url("../assets/images/login-background.jpg");
  background-image: url("../assets/images/bg-login.png");
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  color: #707070;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .go-register {
    color: red;
    font-size: 16px;

    i {
      font-size: 18px;
      top: 3px;
    }
  }
}

.password-set {

  :deep(.el-form-item__content) {
    width: 100%;
    justify-content: space-between;

    // 忘记密码
    .forgot-password {
      color: #aaaaaa;
    }
  }
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  position: relative;
  left: 25%;

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}
.loginBox{
  height: 125px;
  position: absolute;
  top: 30px;left: 50px;
  display: flex;
  flex-direction: row;
  align-items: center;
  img{
    width: 216px;
  }
  span{
    font-size: 40px;
    margin-left: 70px;
    letter-spacing: 1px;
    color: #fff;
    font-weight: 700;
    transform: scale(1.2);
  }
}
</style>